<template>
  <el-drawer with-header :visible.sync="open_schooltimetable" direction="rtl" size="50%" :show-close="false"
    @closed='closed'>
    <div>


      <div v-if="nowscheduling.state=='未开始'">
        <el-alert title="未开始，开课前一小时开放考勤签到，当前可操作请假和调整学员。" type="info" :closable="false">
        </el-alert>

      </div>
      <div v-if="nowscheduling.state=='进行中'">
        <el-alert title="已开放考勤，请及时为学员操作考勤签到" type="success" :closable="false">
        </el-alert>
      </div>
      <div v-if="nowscheduling.state=='待结算'">
        <el-alert title="该课节已过结束时间，请尽快完成结算工作" type="warning" :closable="false">
        </el-alert>
      </div>
      <div v-if="nowscheduling.state=='已结算'">
        <el-alert title="该课节已完成结算" type="success" :closable="false">
        </el-alert>
        <!-- <el-alert title="nowscheduling.totalConsumption" type="success">
           </el-alert> -->
      </div>


      <div class="ml30 mt20">

        <div class=" text-black text-size-20  " style="font-weight: 700"> {{result_numberall}}
          {{nowscheduling.studyDate}} {{week_day}}
        </div>
        <div class="classflex-end mr30">
          <el-button type="primary" @click="Refresh">刷新</el-button>
          <el-button type="primary" @click="Postcomments">发布点评</el-button>
          <el-button type="primary" @click="edittimetable">修改课节</el-button>
          <el-button type="primary" @click="detel">删除课节</el-button>

        </div>
      </div>
      <!-- {{nowscheduling}} -->

      <div class="ml30 mt20 classflex-left">
        <div class=" text-black text-size-40  text-green ">
          <i class="el-icon-alarm-clock mr10"></i>{{nowscheduling.classStart}}-{{nowscheduling.classFinish}}
        </div>
        <div class=" text-black text-size-17  ml20 ">{{nowscheduling.classHours}}课时</div>
      </div>
      <div class="ml30 mt20 classflex-space-between">


        <div class=" mt20  classflex-left">
          <div class=" text-black text-size-20    "><i class="el-icon-user mr10"></i>班级: </div>
          <div class=" text-gray text-size-20  ml10 ">{{nowscheduling.className||"默认班级"}}/{{nowscheduling.classCourse}}
          </div>

        </div>

        <div class="mr30">

        </div>

      </div>
      <div class="ml30 mt20  classflex-left">
        <div class=" text-black text-size-20    "><i class="el-icon-user mr10"></i>授课教师: </div>
        <div class=" text-gray text-size-20  ml10 ">{{nowscheduling.classTeacher}}</div>

      </div>
      <div class="ml30 mt20  classflex-space-between">
        <div class="classflex-left">
          <div class=" text-black text-size-20  text-danger "><i class="el-icon-s-fold mr10"></i>考勤教师: </div>
          <div class=" text-gray text-size-20  ml10 ">{{nowscheduling.classAttendant}}</div>
        </div>
        <div class="mr30">

        </div>
      </div>
      <div class="ml20 mt20">
        <el-tabs v-model="activeName" @tab-click="tabschange">
          <el-tab-pane label="课节学员" name="课节学员"></el-tab-pane>
          <el-tab-pane label="课堂点评" name="课堂点评"></el-tab-pane>


        </el-tabs>
        <div v-if="activeName=='课节学员'" class="wrapper">


          <div class="classflex-space-between">
            <div class="ml10">
              <div>课节学员:{{classrecordsList.length}}人</div>
              <div class="mt20">到课{{Reach}} 请假{{Askforleave}} 未到{{NotYet}} 未考勤{{NotAttendance}}</div>


            </div>
            <div v-if="nowscheduling.state=='未开始'" class="mr30">
              <!-- <el-button type="primary" @click="search">批量考勤</el-button> -->
              <el-button type="primary" @click="addstudent">添加学员</el-button>

            </div>
            <div v-if="nowscheduling.state=='进行中'" class="mr30">
              <!-- <el-button type="primary" @click="search">批量考勤</el-button> -->
              <el-button type="primary" @click="addstudent">添加学员</el-button>
            </div>
            <div v-if="nowscheduling.state=='待结算'" class="mr30">
              <el-button type="primary" @click="settlement" :disabled="disable">立即结算</el-button>
              <!-- <el-button type="primary" @click="search" :disabled="disable">批量考勤</el-button> -->
              <el-button type="primary" @click="addstudent" :disabled="disable">添加学员</el-button>
            </div>
            <div v-if="nowscheduling.state=='已结算'" class="mr30">
              <el-button type="primary" @click="Supplementarysettlement">补充结算</el-button>
            </div>


          </div>
          <el-divider></el-divider>
          <!-- {{classrecordsList}} -->
          <el-empty :image-size="300" v-if="classrecordsList.length==0"></el-empty>
          <div class="   hovercolor stylecard mt10 " v-else :class="selectedIndex1 == index ? 'changecolor':''"
            v-for="(item,index) in classrecordsList" :key="item.id" @click="GetMessage(1,index,item.id)">
            <!-- <el-card shadow="always"> -->

            <div class="classflex-left  mb20 pd10 mt10 ml10">
              <div>

                <img src="@/assets/touxiang.png" alt="">
              </div>
              <div class="ml20" style="width: 20%;">
                <div class=" text-black text-size-20  " :class="selectedIndex1 == index ? 'text-green':''">
                  {{item.studentName}}
                </div>
                <div class="text-gray text-size-14  mt10">剩余{{item.remainingclasshours}}课时</div>
              </div>


              <div class="ml20 classflex-end mr20" style="width: 80%;">

                <div v-if="nowscheduling.state=='已结算'" class="text-size-18 mr20">
                  {{item.attendanceState}}


                </div>
                <div v-else>
                  <!-- {{item}} -->

                  <el-select v-model="item.attendanceState" placeholder="请选择" class="mr10" style="width: 120px;"
                    @change="ChangeAttendanceState(item)">
                    <el-option v-for="items in optionsclass" :key="items.value" :label="items.label"
                      :value="items.value">
                    </el-option>
                  </el-select>
                </div>

                <div v-if="nowscheduling.state=='已结算'" class="text-gray text-size-18  mr10 classflex-left">
                  扣{{item.courseCancellations}} 课时
                </div>

                <div v-else class="text-gray text-size-18  mr10 classflex-left" :disabled="disable">

                  扣
                  <el-input-number class="mr10 ml10" style="width: 100px;" v-model="item.courseCancellations" :min="1"
                    :max="1000" label="描述文字" controls-position="right">
                  </el-input-number>
                  课时

                </div>

                <div class="text-gray text-size-18   mr10" :disabled="disable" v-if="nowscheduling.state=='已结算'">重新结算
                </div>
                <div class="text-gray text-size-18   mr10" :disabled="disable">备注</div>
                <div class="text-gray text-size-18   mr10" @click="removeitem(item.id)" :disabled="disable">移除</div>
              </div>
            </div>

          </div>
        </div>
        <div v-else-if="activeName=='课堂点评'">


        </div>



      </div>



    </div>





    <edit-school-timetable class="" ref="EditSchoolTimetable">

    </edit-school-timetable>
    <add-studentscheduing-drawer class="" ref="addstudentscheduingdrawer" @addClassrecords="addClassrecordlists">

    </add-studentscheduing-drawer>
    <supplement-studentscheduing-drawer class="" ref="supplementstudentscheduingdrawer"
      @supplementClassrecords="addClassrecordlists">

    </supplement-studentscheduing-drawer>

  </el-drawer>


</template>



<script>
  import EditSchoolTimetable from '@/components/EditSchoolTimetable'
  import AddStudentscheduingDrawer from '@/components/AddStudentscheduingDrawer'
  import SupplementStudentscheduingDrawer from '@/components/SupplementStudentscheduingDrawer'

  import {
    listStudent,
    getStudent,
    delStudent,
    addStudent,
    updateStudent
  } from "@/api/student/student";
  import {
    listUser,
    listUser2,
    getUser,
    delUser,
    addUser,
    updateUser,
    resetUserPwd,
    changeUserStatus,
    deptTreeSelect
  } from "@/api/system/user";
  import {
    listCourse,
    getCourse,
    delCourse,
    addCourse,
    updateCourse
  } from "@/api/course/course";
  import {
    listScheduling,
    getScheduling,
    delScheduling,
    addScheduling,
    updateScheduling
  } from "@/api/scheduling/scheduling";
  import {
    listClassrecords,
    getClassrecords,
    delClassrecords,
    addClassrecords,
    updateClassrecords
  } from "@/api/classrecords/classrecords";
  import {
    calculateDaysAfter,
    calculateDaysBetween
  } from "@/utils/ruoyi";
  export default {
    name: 'AddStudentDrawer',
    dicts: ['sys_oper_type', 'student_relationship', 'student_state', 'student_sex', 'enrollment_channels',
      'student_grade'
    ],
    components: {
      EditSchoolTimetable,
      AddStudentscheduingDrawer,
      SupplementStudentscheduingDrawer
    },
    data() {
      return {
        NotAttendance: "0",
        nowallcourseCancellations: 0,
        Reach: "0",
        Askforleave: "0",
        NotYet: "0",
        optionsclass: [{
          value: '到课',
          label: '到课'
        }, {
          value: '请假',
          label: '请假'
        }, {
          value: '未到',
          label: '未到'
        }],
        value: '',
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          studentId: null,
          userState: null,
          userName: null,
          sex: null,
          birthday: null,
          phonenumber: null,
          relationship: null,
          school: null,
          grade: null,
          address: null,
          enrollmentChannels: null,
          followUpPerson: null,
          userAccount: null,
          password: null,
          status: null,
          deptId: null,
          classId: null,
          avatar: null,
          loginIp: null,
          loginDate: null,
          totalClassHours: null,
          remainingClassHours: null,
          accumulatedLearningHours: null,
          label: null,
          remark2: null,
          remark3: null,
          remark4: null,
          remark5: null,
          remark6: null,
          remark7: null,
          remark8: null,
          remark9: null,
          remark10: null
        },
        // 表单参数
        form: {},
        week_day: "",
        activeName: '课节学员',
        result_numberall: '',
        calendardata: "",
        rules_student: {
          userName: [{
              required: true,
              message: '请输入用户姓名',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 5,
              message: '长度在 1 到 5 个字符',
              trigger: 'blur'
            }
          ],
          relationship: [{
            required: true,
            message: '请输入手机号码',
            trigger: 'change'
          }],


          phonenumber: [{
              required: true,
              message: '请输入手机号码',
              trigger: 'change'
            },
            {
              min: 11,
              max: 12,
              message: '长度在 11 到 12 个字符',
              trigger: 'blur'
            }
          ],

        },
        form2: {},
        rules_student2: {
          userName: [{
              required: true,
              message: '请输入用户姓名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 5,
              message: '长度在 3 到 5 个字符',
              trigger: 'blur'
            }
          ],
          relationship: [{
            required: true,
            message: '请输入手机号码',
            trigger: 'change'
          }],


          phonenumber: [{
              required: true,
              message: '请输入手机号码',
              trigger: 'change'
            },
            {
              min: 11,
              max: 12,
              message: '长度在 11 到 12 个字符',
              trigger: 'blur'
            }
          ],

        },
        type: false,
        open_schooltimetable: false,

        showtype: true,
        options: [],
        userList: [],
        studentList: [],
        queryParamsTeacher: {},
        selectedIndex1: 0,
        courseList: [],
        queryParamsCourse: {},
        nowscheduling: {},
        queryParamsScheduling: {},
        queryParamsClassrecords: {},
        classrecordsList: [],
        disable: false,
        formupdateScheduling: {},
        formClassrecords: {}
      }
    },
    props: {

      title: {
        default: "",
        type: String,
      },


    },
    computed: {

    },
    watch: {

    },
    created() {
      // this.getStudentList();
      // this.getCourseList();

    },

    methods: {
      Postcomments() {

      },
      closed() {
        console.log("关闭了");
        this.$emit('closeSchoolTimetableDrawer', 'addsuccess'); // 触发名为'childEvent'的自定义事件，并传递数据
      },
      ChangeAttendanceState(e) {
        // console.log("改变了"+JSON.stringify(e));
        this.formClassrecords.scheduleId = e.scheduleId;
        this.formClassrecords.attendanceState = e.attendanceState;
        this.formClassrecords.id = e.id;

        updateClassrecords(this.formClassrecords).then(response => {
          this.getClassrecordList();
          this.$modal.msgSuccess("操作成功");


        });

      },
      addClassrecordlists() {
        console.log("该刷新了");
        this.getClassrecordList();


      },
      addstudent() {
        this.$refs.addstudentscheduingdrawer.open_studentlistdrawer(this.nowscheduling.id);


      },
      Supplementarysettlement() {
        this.$refs.supplementstudentscheduingdrawer.open_studentlistdrawer(this.nowscheduling.id, this.nowscheduling
          .classCourseId);


      },
      edittimetable() {
        // EditSchoolTimetable
        this.$refs.EditSchoolTimetable.open_schooltimetableedit(this.nowscheduling.id);

      },
      Refresh() {
        this.getSchedulings();
      },
      settlement() {

        console.log(this.NotAttendance);
        if (this.NotAttendance != 0) {

          this.$modal.msgError("请选择学生上课状态");
        } else {




          var allcourseCancellations = 0;
          var arr = [];
          for (var i = 0; i < this.classrecordsList.length; i++) {
            var data = {}

            //记录ID
            data.id = this.classrecordsList[i].id;
            data.studentId = this.classrecordsList[i].studentId;
            data.studentName = this.classrecordsList[i].studentName;
            data.scheduleId = this.nowscheduling.id;
            data.courseId = this.nowscheduling.classCourseId;
            data.deptId = this.classrecordsList[i].deptId;
            //扣费时长
            data.courseCancellations = this.classrecordsList[i].courseCancellations;
            data.settlestatus = "已结算"
            arr.push(data);
            allcourseCancellations = allcourseCancellations + this.classrecordsList[i].courseCancellations
          }
          this.nowallcourseCancellations = allcourseCancellations;
          if (arr.length > 0) {
            var q = 0;
            for (var w = 0; w < arr.length; w++) {

              updateClassrecords(arr[w]).then(response => {
                q++;
                console.log("更新记录" + q);
                // console.log(arr.length);
                if (q == arr.length) {
                  //设置学生人数
                  this.formupdateScheduling.classStudent = arr.length;
                  this.formupdateScheduling.totalConsumption = this.nowallcourseCancellations;
                  this.formupdateScheduling.id = this.queryParamsScheduling.id;
                  this.formupdateScheduling.state = "已结算";
                  updateScheduling(this.formupdateScheduling).then(response => {
                    this.$modal.msgSuccess("结算成功");

                    setTimeout(this.getSchedulings(), 3000);
                    
                  });

                }


              });
            }
          } else {
            this.$modal.msgSuccess("请选择结算的数据");
          }
        }








      },

      removeitem(id) {
        this.$modal.confirm('是否确认删除此记录？').then(function() {
          return delClassrecords(id);
        }).then(() => {
          this.getClassrecordList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});

      },
      /** 查询上课记录列表 */
      getClassrecordList() {
        //设置排课ID
        this.disable = true;
        this.queryParamsClassrecords.deptId = this.$store.state.user.deptId;
        listClassrecords(this.queryParamsClassrecords).then(response => {
          this.classrecordsList = response.rows;
          this.countnumber();
          this.disable = false;
        });
      },
      getWeekDay(date) {
        if (typeof date === 'string') {
          date = date.replace(/-/g, '/')
        }

        const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        const myDate = new Date(Date.parse(date));
        return weekDay[myDate.getDay()];
      },

      formatDate(date) {
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);

        return `${year}-${month}-${day} `;
      },
      formatDate2(date) {
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);

        return `${year}年${month}月${day}日 `;
      },
      formatDate3(date) {
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);

        return `${year}年${month}月  `;
      },
      startnow() {
        // console.log("zz1" + this.calendardata);
        // console.log("zz2" + this.formatDate(new Date()));
        var result_number = this.calculateDaysBetween(this.calendardata.replaceAll("-", "/"), this.formatDate(
          new Date()));

        if (result_number == 0) {
          this.result_numberall = "今天"
        } else {
          if (this.calendardata > this.formatDate(new Date())) {
            result_number = result_number + "天后";
          } else {
            // console.log("前");
            result_number = result_number + "天前";
          }
          this.result_numberall = result_number
        }


        var WeekDay = this.getWeekDay(this.calendardata);
        this.week_day = WeekDay;
        // var month = this.formatDate3(this.calendardata);
        // this.now_month = month;
      },
      // getSchedulingList() {

      //   this.queryParamsScheduling.deptId = this.$store.state.user.deptId;
      //   listScheduling(this.queryParamsScheduling).then(response => {
      //     this.schedulingList = response.rows;
      //     this.nowscheduling = this.schedulingList[0];
      //     this.calendardata = this.nowscheduling.studyDate;
      //     this.startnow();

      //   });
      // },

      tabschange(tab, event) {
        console.log(tab.name);
        if (tab.name == "在读学员") {

          this.queryParams.userState = "在读学员";



        } else if (tab.name == "历史学员") {

          this.queryParams.userState = "历史学员";

        } else if (tab.name == "潜在学员") {

          this.queryParams.userState = "潜在学员";

        }
        this.loading = true;
        this.queryParams.deptId = this.$store.state.user.deptId;
        listStudent(this.queryParams).then(response => {
          this.studentList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },

      GetMessage(type, index, id) {

        this.selectedIndex1 = index;

      },
      search() {

      },

      openschooltimetable(id) {

        // console.log("值" + id);
        this.open_schooltimetable = true;
        this.queryParamsScheduling.id = id;
        this.queryParamsClassrecords.scheduleId = id;

        this.getSchedulings();

      },
      getSchedulings() {
        getScheduling(this.queryParamsScheduling.id).then(response => {
          this.nowscheduling = response.data;
          this.calendardata = this.nowscheduling.studyDate;
          // this.$modal.msgSuccess("获取数据成功");
          this.countnumber();
          this.startnow();
          this.getClassrecordList();
        });
      },
      // 取消按钮
      cancel() {
        this.open_schooltimetable = false;
        this.reset();
      },


      detel() {
        const ids = this.queryParamsScheduling.id;
        this.$modal.confirm('是否确认删除此课程？').then(function() {
          return delScheduling(ids);
        }).then(() => {
          this.open_schooltimetable = false;
          this.reset();
          this.$modal.msgSuccess("删除成功");
          this.$emit('detel', 'detel');

        }).catch(() => {});
      },
      countnumber() {
        console.log("测试开始" + this.classrecordsList.length);
        var list0 = this.classrecordsList.filter(function(item, index, arrs) {
          return item.attendanceState == '' || item.attendanceState == null;
        });
        // console.log(list0.length);
        this.NotAttendance = list0.length;


        var list1 = this.classrecordsList.filter(function(item, index, arrs) {
          return item.attendanceState == '到课';
        });
        console.log(list1);
        // console.log(list1.length);
        this.Reach = list1.length;
        var list2 = this.classrecordsList.filter(function(item, index, arrs) {

          return item.attendanceState == '请假';
        });
        this.Askforleave = list2.length;
        var list3 = this.classrecordsList.filter(function(item, index, arrs) {
          return item.attendanceState == '未到';
        });
        this.NotYet = list3.length;
      },








      // 表单重置
      reset() {
        this.form = {
          id: null,
          studentId: null,
          userState: null,
          userName: null,
          sex: null,
          birthday: null,
          phonenumber: null,
          relationship: null,
          school: null,
          grade: null,
          address: null,
          enrollmentChannels: null,
          followUpPerson: null,
          userAccount: null,
          password: null,
          status: null,
          deptId: null,
          classId: null,
          delFlag: null,
          avatar: null,
          loginIp: null,
          loginDate: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          totalClassHours: null,
          remainingClassHours: null,
          accumulatedLearningHours: null,
          label: null,
          remark: null,
          remark2: null,
          remark3: null,
          remark4: null,
          remark5: null,
          remark6: null,
          remark7: null,
          remark8: null,
          remark9: null,
          remark10: null
        };
        this.resetForm("form");
      },


    }





  }
</script>

<style lang="scss" scoped>
  .rightPanel-background {
    position: fixed;
    top: 0;
    left: 0;
    opacity: 0;
    transition: opacity .3s cubic-bezier(.7, .3, .1, 1);
    background: rgba(0, 0, 0, .2);
    z-index: -1;
  }

  .rightPanel {
    width: 100%;
    max-width: 260px;
    height: 100vh;
    position: fixed;
    top: 0;
    right: 0;
    box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, .05);
    transition: all .25s cubic-bezier(.7, .3, .1, 1);
    transform: translate(100%);
    background: #fff;
    z-index: 40000;
  }

  .handle-button {
    width: 48px;
    height: 48px;
    position: absolute;
    left: -48px;
    text-align: center;
    font-size: 24px;
    border-radius: 6px 0 0 6px !important;
    z-index: 0;
    pointer-events: auto;
    cursor: pointer;
    color: #fff;
    line-height: 48px;

    i {
      font-size: 24px;
      line-height: 48px;
    }
  }
</style>
